package deviceSyc;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeoutException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.ShutdownSignalException;

/**
 * 读取队列的程序端，实现了Runnable接口。
 * 
 * @author xueyu
 * 
 */
public class MQConsumer extends MQCon implements Runnable, Consumer {
//	private static Logger log = LoggerFactory.getLogger(MQConsumer.class);																						// 缓存请求
	private String DEVICESYC_REQUEST = routingKey;// 设备同步请求信息
	private String DEVICESYC_FEBACK = bindingKey;// 设备同步反馈信息
	
	FileUtil fu = new FileUtil();
	String JSONStr = fu.ReadFile(rootPath + "/res/scUrl.json");
	JSONAnalysis ja = new JSONAnalysis();
	List<JSONObject> urlObjList = ja.URLParse(JSONStr);

	public static void main(String[] args) throws IOException, TimeoutException {
        MQConsumer mqr = new MQConsumer();
		mqr.run();
    }
	
	public MQConsumer() throws IOException {
		super();
	}

	public void run() {
		try {
			// start consuming messages. Auto acknowledge messages.
//			channel.queueBind(queueName,exchangeName,DEVICESYC_REQUEST+"110");
//			remove the cityCode
//			for(int i=0;i<urlObjList.size();i++){
//				JSONObject obj = urlObjList.get(i);
//				channel.queueBind(queueName, exchangeName, DEVICESYC_FEBACK+obj.getString("cityCode"));
//			}
			channel.queueBind(queueName, exchangeName, DEVICESYC_FEBACK);
//			channel.queueBind(queueName, exchangeName, DEVICESYC_REQUEST);
			// channel.queueBind(queueName,exchangeName,"vm_cplc_response");
			channel.basicConsume(queueName, true, this);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Called when consumer is registered.
	 */
	public void handleConsumeOk(String consumerTag) {
		System.out.println("Consumer " + consumerTag + " registered");
	}

	/**
	 * Called when new message is available.
	 */
	public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
			throws IOException {
		String message = new String(body, "UTF-8");
		System.out.println(message+ " received."+"   env="+envelope.getRoutingKey());
//        log.info(message+ " received."+"   env="+envelope.getRoutingKey());
	}

	public void handleCancel(String consumerTag) {
	}

	public void handleCancelOk(String consumerTag) {
	}

	public void handleRecoverOk(String consumerTag) {
	}

	public void handleShutdownSignal(String consumerTag, ShutdownSignalException arg1) {
	}
}
